package com.lebang.medicalInquiry.controller.sys;


import com.lebang.medicalInquiry.component.TokenComponent;
import com.lebang.medicalInquiry.constant.UserConstants;
import com.lebang.medicalInquiry.model.po.SysMenu;
import com.lebang.medicalInquiry.model.po.SysUser;
import com.lebang.medicalInquiry.model.vo.Ztree;
import com.lebang.medicalInquiry.response.Callback;
import com.lebang.medicalInquiry.response.JsonData;
import com.lebang.medicalInquiry.service.SysMenuService;
import com.lebang.medicalInquiry.util.AuthorizationUtils;
import com.lebang.medicalInquiry.utils.TextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zpc
 * @version V1.0
 * @date 2021-05-12
 */
@Api(tags = "【web端】菜单权限")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService menuService;
    @Autowired
    private TokenComponent tokenComponent;

    @RequiresPermissions(value = {"sys:menu:get"})
    @ApiOperation("查询所有菜单")
    @GetMapping("/")
    public JsonData list(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(name = "menuName", required = false) String menuName,
                         @RequestParam(name = "visible", required = false) Integer visible) {


        try {
            List<SysMenu> menuList = menuService.selectMenuList(menuName, visible);
            return Callback.success("200", "成功", menuList);
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }
    }

    /**
     * 删除菜单
     */
    @RequiresPermissions(value = {"sys:menu:delete"})
    @ApiOperation("删除菜单")
    @DeleteMapping("/{menuId}")
    public JsonData remove(@PathVariable("menuId") Long menuId) {

        try {
            if (menuService.selectCountMenuByParentId(menuId) > 0) {
                return Callback.fail("505", "存在子菜单,不允许删除");
            }
            if (menuService.selectCountRoleMenuByMenuId(menuId) > 0) {
                return Callback.fail("505", "菜单已分配,不允许删除");
            }
            menuService.deleteMenuById(menuId);
            AuthorizationUtils.clearAllCachedAuthorizationInfo();
            return Callback.success("200", "删除成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }
    }

    /**
     * 新增保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:post"})
    @ApiOperation("新增保存菜单")
    @PostMapping("/")
    public JsonData addSave(HttpServletRequest servletRequest, @RequestBody SysMenu menu) {


        try {
            if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
                return Callback.fail("505", "新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
            }
            String authorization = servletRequest.getHeader("Authorization");
            SysUser byToken = tokenComponent.getByToken(authorization);
            if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
                return Callback.fail("404", "暂无用户信息");
            }
            menu.setCreateBy(byToken.getLoginName());
            menuService.insertMenu(menu);
            AuthorizationUtils.clearAllCachedAuthorizationInfo();
            return Callback.success("200", "添加成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }


    }

    /**
     * 修改保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:put"})
    @ApiOperation("修改保存菜单")
    @PutMapping("/")
    public JsonData editSave(HttpServletRequest servletRequest, @RequestBody SysMenu menu) {


        try {
            if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
                return Callback.fail("505", "修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
            }
            String authorization = servletRequest.getHeader("Authorization");
            SysUser byToken = tokenComponent.getByToken(authorization);
            if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
                return Callback.fail("404", "暂无用户信息");
            }
            menu.setCreateBy(byToken.getLoginName());
            menuService.updateMenu(menu);
            AuthorizationUtils.clearAllCachedAuthorizationInfo();
            return Callback.success("200", "修改成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }

    }

    /**
     * 加载角色菜单列表树
     */
    @RequiresPermissions(value = {"sys:menu:role:get"})
    @ApiOperation("加载角色菜单列表")
    @GetMapping("/role")
    public JsonData roleMenuTreeData(HttpServletRequest servletRequest, Long roleId) {
        try {
            String authorization = servletRequest.getHeader("Authorization");
            SysUser byToken = tokenComponent.getByToken(authorization);
            if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
                return Callback.fail("404", "暂无用户信息");
            }
            List<Ztree> ztrees = menuService.roleMenuTreeData(roleId, null);
            return Callback.fail("200", "成功", ztrees);
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }
    }
    /**
     * 新增保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:import:post"})
    @ApiOperation("导入菜单")
    @PostMapping("/import")
    public JsonData importMenu(HttpServletRequest servletRequest, @RequestBody List<SysMenu> menus) {

            String authorization = servletRequest.getHeader("Authorization");
            SysUser byToken = tokenComponent.getByToken(authorization);
            if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
                return Callback.fail("404", "暂无用户信息");
            }
            menuService.importMenu(menus,byToken.getLoginName());
            AuthorizationUtils.clearAllCachedAuthorizationInfo();
            return Callback.success("200", "添加成功");
    }
    /**
     * 新增保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:export:get"})
    @ApiOperation("导出菜单")
    @GetMapping("/export")
    public JsonData exportMenu(HttpServletRequest servletRequest, HttpServletResponse response) {
        List<SysMenu> all = menuService.getAll();
        try {

            return Callback.success("200","导出成功",all);

        } catch (Exception e) {
          e.printStackTrace();
        }
        return Callback.fail("500", "异常");

    }
}
